package sfs

import (
	"context"
	"github.com/chicken-team-outside/chicken_transmission/api_messages"
	"github.com/chicken-team-outside/chicken_transmission/driver"
	"github.com/golang/protobuf/proto"
	"go.uber.org/zap"
	"os"
)

func osFileInfoToApiMessage(info os.FileInfo) *api_messages.FileInfo {
	return &api_messages.FileInfo{
		Name:    info.Name(),
		Size:    info.Size(),
		Mode:    uint32(info.Mode()),
		ModTime: info.ModTime().UnixMilli(),
		IsDir:   info.IsDir(),
	}
}

func (p *FsClient) Stat(ctx context.Context, clientId uint64, path string) (*FileInfo, error) {
	request, err := p.sendRequest(ctx, clientId, api_messages.MessageType_Stat, &api_messages.PathMessage{Path: path})
	if err != nil {
		return nil, err
	}
	info := new(api_messages.StatResponse)
	err = proto.Unmarshal(request, info)
	if err == nil {
		err = decodeStatusMessageDirect(info.Status)
	}
	if err != nil {
		return nil, err
	}
	return &FileInfo{FileInfo: info.Result}, nil
}

func (p *FsClient) statProvider(ctx context.Context, header *api_messages.MessageHeader, data []byte) {
	if ctx.Err() == nil {
		path := new(api_messages.PathMessage)
		err := proto.Unmarshal(data, path)
		var client driver.LocalDriver
		if err == nil {
			client = p.GetLocal()
			if client == nil {
				err = ErrNotSetLocalDriver
			}
		}
		var info os.FileInfo
		if err == nil {
			info, err = client.Stat(path.Path)
		}
		result := &api_messages.StatResponse{Status: encodeStatusMessage(err)}
		if err == nil {
			result.Result = osFileInfoToApiMessage(info)
		}
		err = p.sendReplyByHeader(ctx, header, result)
		if err != nil {
			zap.L().Warn("error sending request", zap.Error(err), zap.Any("query", path), zap.Any("header", header))
		}
	}
}
